<?php

namespace App\Models;

use App\Http\Controllers\ScoreRuleController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Exp;

/**
 * 座位特殊排班表
 * Class ReservationModel
 * @package app\common\model
 */
class ReservationSpecialSchedule extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    public $table = 'reservation_special_schedule';

    /**
     * 修改预约排版
     */
    public function change($data, $field = [], $findWhere = [])
    {
        //本次提交的数据
        $reservation_id = $data['reservation_id'];
        $date = $data['date'];
        $time = $data['time'];
        $name = $data['name'];
        if (is_string($time)) {
            $time = json_decode($time, true);
        }
        $datas = [];
        $timeData = [];
        if ($time) {
            foreach ($time as $key => $val) {
                if (empty($val['start_time']) || empty($val['end_time'])) {
                    throw new Exception("时间格式不正确");
                }
                $temp['reservation_id'] = $reservation_id;
                $temp['date'] = $date;
                $temp['name'] = $name;
                $temp['start_time'] = $val['start_time'];
                $temp['end_time'] = $val['end_time'];
                $temp['create_time'] = date("Y-m-d H:i:s", time());
                $datas[] = $temp;

                $time['start_time'] = $val['start_time'];
                $time['end_time'] = $val['end_time'];
                $timeData[] = $time;
            }
            $timeOver = compare_date($timeData);
            if (!$timeOver) {
                throw new Exception("排版时间不能有交叉");
            }
        } else {
            $temp['reservation_id'] = $reservation_id;
            $temp['date'] = $date;
            $temp['name'] = $name;
            $temp['start_time'] = null;
            $temp['end_time'] = null;
            $temp['create_time'] = date("Y-m-d H:i:s", time());
            $datas[] = $temp;
        }
        //删除所有排版，排版数据不会太多，直接删除
        $this->where('reservation_id', $reservation_id)
            ->where('date', $date)
            ->where('is_del', 1)
            ->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);
        $this->insert($datas);
    }


    /**
     * 预约特殊日期排班列表
     * @param reservation_id int 预约id 预约id 特殊为 0
     * @param keywords string 搜索筛选
     * @param limit int 限制条数
     * @param start_date date 开始时间
     * @param end_date date 结束时间
     */
    public function lists($reservation_id, $keywords = null, $start_date = null, $end_date = null, $limit = 10)
    {
        $res =  $this->select('id', 'name', "date", DB::raw("GROUP_CONCAT(start_time,'~',end_time) as time"), "reservation_id", 'create_time')
            ->where('reservation_id', $reservation_id)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name', 'like', "%$keywords%");
                }
            })
            ->where(function ($query) use ($start_date, $end_date) {
                if ($start_date) {

                    $query->where('date', '>=', $start_date);
                }
                if ($end_date) {
                    $query->where('date', '<=', $end_date);
                }
            })
            ->where('is_del', 1)
            ->orderByDesc('date')
            ->groupBy('date')
            ->paginate($limit)
            ->toArray();
        return $res;
    }

    /**
     * 详情
     */
    public function detail($id, $field = [])
    {
        $res = $this->where('id', $id)->where('is_del', 1)->first();
        if (empty($res)) {
            return [];
        }
        if (empty($field)) {
            $field = ["start_time", "end_time"];
        }
        $time = $this->select($field)->where('reservation_id', $res->reservation_id)
            ->where('date', $res->date)
            ->where('is_del', 1)
            ->get()
            ->toArray();
        $data['name'] = $res['name'];
        $data['date'] = $res['date'];
        $data['time'] = $time;
        return $data;
    }

    /**
     * 通过预约id和日期查询预约信息
     * @param $reservation_id int 预约id
     * @param $date date 日期
     * */
    public function getSpecialListByDate($reservation_id, $date, $field = [])
    {
        $date = date('Y-m-d', strtotime($date));
        if (empty($field)) {
            $field = ['id', 'name', 'date', 'start_time', 'end_time', 'reservation_id'];
        }
        $res = $this->select($field)
            ->where('is_del', 1)
            ->where('date', $date)
            ->where(function ($query) use ($reservation_id) {
                if ($reservation_id) {
                    $query->where('reservation_id', $reservation_id)->orWhere('reservation_id', 0);
                }
            })
            ->groupBy('start_time')
            ->get()
            ->toArray();
        return $res;
    }

    /**
     * 通过预约id和日期查询预约信息 （扫码时使用）
     * @param $reservation_id int 预约id
     * @param $date date 日期
     * */
    public function getSpecialScheduleInfo($reservation_id, $date, $field = [])
    {
        $date = date('Y-m-d', strtotime($date));
        if (empty($field)) {
            $field = ['id', 'name', 'date', 'start_time', 'end_time', 'reservation_id'];
        }
        $res = $this->select($field)
            ->where('is_del', 1)
            ->where('date', $date)
            ->where(function ($query) use ($reservation_id) {
                if ($reservation_id) {
                    $query->where('reservation_id', $reservation_id)->orWhere('reservation_id', 0);
                }
            })
            ->where('start_time', '<', date('H:i:s', time() + 600)) //可以提前 10 分钟进去
            ->where('end_time', '>', date('H:i:s'))
            ->get()
            ->toArray();
        return $res;
    }
}
